<template>
  <view class="shop">
    <view class="fix_top_box">
      <view class="address_box" @tap="goLink('/pages/shop/selfGet')">
        <view class="fn-sz-26 fn-cl-333333 mar-right-8">
          选择配送点：{{ curAddressGetPoint.name ? curAddressGetPoint.name : '' }}</view>
        <view>
          <image class="icon-30" src="../../static/images/icon/icon_bottom_arr.png" mode=""></image>
        </view>
      </view>
      <view class="search_box" @tap="goLink('/pages/shop/shopSearchPage')">
        <view class="left_search_box">
          <view class="search_icon">
            <image src="../../static/images/icon/icon_search.png" class="icon-32" mode=""></image>
          </view>
          <view class="search_input">请输入搜索内容</view>
        </view>
        <view class="search_btn"><button>搜索</button></view>
      </view>
    </view>
    <view class="carousel_box">
      <Carousel :val="bannerObj" @swiperClick="swiperClick"></Carousel>
    </view>
    <view class="classify_list_box">
      <u-grid :border="false" col="5">
        <u-grid-item v-for="(item, index) in classiyList" :key="index">
          <view class="classify_item" @tap="goClassify(item, 'team_category_id')">
            <image :src="item.image" class="icon-80" mode=""></image>
            <view class="fn-sz-24">{{ item.name }}</view>
          </view>
        </u-grid-item>
        <u-grid-item>
          <view class="classify_item" @tap="goClassifyPage">
            <image src="../../static/images/icon/icon_all.png" class="icon-80" mode=""></image>
            <view class="fn-sz-24">全部</view>
          </view>
        </u-grid-item>
      </u-grid>
    </view>
    <view class="newcomer_box" v-if="isNewPerson">
      <view class="newcomer_top_box">
        <view class="fn-sz-30">新人特惠</view>
        <view class="more_btn" @tap="goLink('/pages/shop/newPersonList')">
          <view class="fn-sz-28">更多</view>
          <image class="icon-28" src="../../static/images/icon/icon_moer_btn.png" mode=""></image>
        </view>
      </view>
      <!-- 新人特惠 -->
      <view class="newcomer_list_box">
        <scroll-view scroll-x scroll-with-animation class="newcomer_scroll_box">
          <view class="innerList">
            <view class="newcomer_shop_item" v-for="item in newcomerList" :key="item.id" @tap.stop="goShopDetails(item.id)">
              <view class="newcomer_shop_item_img">
                <image :src="item.images[0]" mode="aspectFill"></image>
              </view>
              <view class="newcomer_shop_item_name">{{ item.name }}</view>
              <view class="newcomer_shop_item_price_box">
                <view class="price_num">
                  <span class="fn-sz-22 fn-cl-F34035">￥</span>
                  <span class="fn-sz-30 fn-cl-F34035">{{ item.new_price }}</span>
                </view>
                <view class="add_shoping_car" @tap.stop="addCarFunc(item)">
                  <image class="icon-40" src="../../static/images/icon/icon_shoping_car_big.png" mode=""></image>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 精品推荐 -->
    <view class="recommend_box">
      <view class="fn-sz-32 mar-bottom-20">精品推荐</view>
      <view class="big_recommend_list">
        <view class="big_recommend_item" v-for="item in recommendList.bigList" :key="item.id" @tap="goClassify(item, 'team_active_id')">
          <image :src="item.image" mode="aspectFill"></image>
        </view>
      </view>
      <view class="small_recommend_list">
        <view class="small_recommend_item" v-for="(item, index) in recommendList.smallList" :key="item.id"
          @tap="goBannerClassify(index, 'team_active_id')">
          <image :src="item.image" mode="aspectFill"></image>
        </view>
      </view>
    </view>
    <!-- 生鲜列表 -->
    <view class="goods_list">
      <GoodsList :list="goodsList.lists" @openCar="openCar"></GoodsList>
      <u-loadmore :status="loadMoreStatus" v-if="goodsList.lists.length" />
    </view>
    <view class="fix_shoping_car">
      <view class="shoping_car_bottom_op_box">
        <view class="shoping_car_bottom_left_box">
          <view class="shoping_car_image" @tap="openShopingCar">
            <image class="icon-100" src="../../static/images/icon/icon_shoping_car_big.png" mode=""></image>
            <view class="shoping_car_num">{{ totalGoodsNum }}</view>
          </view>
          <view class="shoping_car_total_pirce_box">
            <view class="fn-sz-24 fn-cl-666666">
              <span class="mar-right-10">合计金额:</span>
              ￥{{ totalPrice }}
            </view>
            <view class="fn-sz-24 fn-cl-666666">
              <span class="mar-right-10">商品数量:</span>
              {{ totalGoodsNum }}
            </view>
          </view>
        </view>
        <view class="go_settle" @tap="goCreateOrder">去结算(￥{{ totalPrice }})</view>
      </view>
    </view>

    <ShopingCar ref="shopingCar"></ShopingCar>
    <buyGoodsPopup ref="buyGoodsPopup" :goodsInfo="curCarItem" popupType="list"></buyGoodsPopup>

    <!-- 优惠券模态框 -->
    <u-popup :show="couponsShow" mode="bottom" @close="couponsClose">
      <view class="couponsModel">
        <view class="coupons_model_top">
          <view class="fn-sz-28 fn-cl-222222">优惠券</view>
          <image @tap="couponsClose" class="icon-36" src="../../static/images/icon/icon_gary_radios_fill.png" mode=""></image>
        </view>
        <scroll-view scroll-y scroll-with-animation class="coupons_scroll_box">
          <view class="coupons_list">
            <view class="coupons_item" v-for="(item, index) in ticket" :key="index" @tap="getTicket(item.id)">
              <view class="coupons_left_price_box fn-cl-F34035">
                <view class="">
                  <span class="fn-sz-26">￥</span>
                  <span class="fn-sz-52">{{ numberToFix(item.price) }}</span>
                </view>
                <view class="fn-sz-20">满{{ item.full_use }}可用</view>
              </view>
              <view class="coupons_right_date_box">
                <view class="fn-sz-28 mar-bottom-10">有效期</view>
                <view class="fn-sz-24 fn-cl-999999">{{ item.start_date }}至{{ item.end_date }}</view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
var QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
import {
  mapGetters,
  mapMutations
} from 'vuex';
import Carousel from '../../components/carousel/Carousel.vue';
import GoodsList from '../../components/goodsList/goodsList.vue';
import Com from '../../mixin/index.js';
import buyGoodsPopup from '../../components/buyGoodsPopup/buyGoodsPopup.vue';
import ShopingCar from '../../components/shopingCar/shopingCar.vue';
export default {
  components: {
    Carousel,
    GoodsList,
    ShopingCar,
    buyGoodsPopup
  },
  mixins: [Com],
  data () {
    return {
      bannerObj: {
        list: [],
        height: '270rpx',
        radius: '10rpx'
      },
      addressObj: {
        address: '',
        latitude: '',
        longitude: ''
      },
      classiyList: [],
      newcomerList: [],
      curAddressGetPoint: {},
      recommendList: {
        bigList: [],
        smallList: []
      },
      curCarItem: {},
      page: {
        page: 1,
        page_size: 6
      },
      teamListObj: {
        lists: [],
        total: 1,
        total_page: 0
      },
      tempPage: {
        page: 1,
        page_size: 6
      },
      isNewPerson: false,
      couponsShow: false,
      ticket: []
    };
  },
  onLoad () {
    qqmapsdk = new QQMapWX({
      key: 'LPPBZ-KHRKX-U5K4E-ZLQSE-6SZJZ-KDBKQ' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
    });
  },
  onPullDownRefresh () {
    this.getProductList({
      team_id: this.curAddressGetPoint.id
    }, 'init').then(res => {
      uni.stopPullDownRefresh();
    });
  },
  onShow () {
    //取消存储以前的地址
    // if (!uni.getStorageSync('cur_address_point')) {
    this.getUserLocation();
    // } else {
    // 	console.log(this.curAddressGetPoint, '当前地址');
    // 	this.curAddressGetPoint = uni.getStorageSync('cur_address_point');
    // 	//防止多次渲染
    // 	if (!this.goodsList.lists.length && this.goodsList.total == 1) {
    // 		this.getProductList({
    // 			team_id: this.curAddressGetPoint.id
    // 		});
    // 	}
    // 	this.getClassify();
    // 	this.getRecommend();
    // 	this.getNewcomerList();
    // 	this.getCouponsList();
    // }
  },
  onReachBottom () {
    this.getProductList({
      team_id: this.curAddressGetPoint.id
    });
  },
  computed: {
    ...mapGetters(['totalGoodsNum', 'totalPrice'])
  },
  methods: {
    ...mapMutations(['SET_SHOPING_CAR_LIST']),
    goLink (url) {
      uni.navigateTo({
        url
      });
    },
    goShopDetails (id) {
      uni.navigateTo({
        url: `/pages/shop/shopDetails?product_id=${id}&addressId=${this.curAddressGetPoint.id}`
      });
    },
    async getClassify () {
      const {
        data
      } = await this.$api.getCate();
      this.bannerObj.list = data.banner;
      this.classiyList = data.lists.slice(0, 9);
      uni.setStorageSync('category_banner', data.category_banner);
      console.log(data, '获取信息');
    },
    testClick () {
      uni.openSetting({
        success (res) {
          console.log(res.authSetting);
        }
      });
    },
    goClassifyPage () {
      uni.switchTab({
        url: '/pages/classifyPage/classifyPage'
      })
    },
    checkNew () {
      return new Promise((reslove, reject) => {
        let token = uni.getStorageSync('token');
        if (token) {
          this.$api.checkNew().then(res => {
            if (res.data.is_new == 1) {
              this.isNewPerson = true;
              reslove();
            } else {
              this.isNewPerson = false;
              reslove();
            }
          });
        } else {
          reslove();
        }
      });
    },
    swiperClick (val) {
      let clickType = this.bannerObj.list[val];
      console.log(clickType, '点击你几个我爱唯欧你');
      switch (clickType.type) {
        case 'none':
          break;
        case 'team':
          this.goShopDetails(clickType.third_id);
          break;
        case 'tour':
          uni.navigateTo({
            url: `/pages/travel/travelDetails?tour_id=${clickType.third_id}`
          });
          break;
      }
    },
    getNewcomerList () {
      this.checkNew().then(res => {
        if (this.isNewPerson) {
          let params = {
            page: 1,
            page_size: 30,
            team_id: this.curAddressGetPoint.id,
            is_new: 1
          };
          this.$api.getProductList(params).then(res => {
            this.newcomerList = res.data.lists;
          });
        }
      });
    },
    //选择地址后重置列表
    initGoodsList () {
      this.curAddressGetPoint = uni.getStorageSync('cur_address_point');
      this.getProductList({
        team_id: this.curAddressGetPoint.id
      }, 'init');
    },
    getRecommend () {
      this.$api.getRecommend().then(res => {
        console.log(res, '获取的推荐模块');
        this.recommendList.bigList = res.data.lists.slice(0, 2);
        this.recommendList.smallList = res.data.lists.slice(2, res.data.lists.length);
        uni.setStorageSync('shop_recommend_list', this.recommendList.smallList);
        console.log(this.recommendList, '呜呜呜');
      });
    },
    goBannerClassify (idx, type) {
      uni.navigateTo({
        url: `/pages/bannerClassifyPage/index?idx=${idx}&type=${type}`
      });
    },
    goClassify (cls, type) {
      uni.navigateTo({
        url: `/pages/shop/classifyPage?clsObj=${JSON.stringify(cls)}&type=${type}`
      });
    },
    goCreateOrder () {
      if (this.totalGoodsNum) {
        uni.navigateTo({
          url: `/pages/shop/goodsSubmitOrder?type=car`
        });
      } else {
        this.$helper.toast('购物车是空的!');
      }
    },
    openShopingCar () {
      if (this.totalGoodsNum) {
        this.$refs.shopingCar.shopingCarShow = true;
      } else {
        this.$helper.toast('购物车是空的!');
      }
    },
    addCarFunc (item) {
      const {
        name,
        new_price,
        price,
        id,
        images
      } = item;
      let params = {
        name,
        new_price,
        price,
        id,
        images,
        num: 1
      };
      var isNewGoods = false;
      if (Number(new_price)) {
        isNewGoods = true;
        params.price = new_price;
      }
      let isHave = false;
      let shopingCarList = this.$store.state.shopingCarList.map(elem => elem);
      let goods_ids = `${params.id}-${params.num}`;
      let arr = [goods_ids];
      shopingCarList.forEach((item, index) => {
        if (item.id != params.id) {
          arr.push(`${item.id}-${item.num}`)
        }
      });

      this.$api.checkBuyLimit({
        goods: arr + ''
      }).then(async res => {
        let {
          data
        } = await this.$api.checkBuyNumLimit({
          goods: arr + ''
        });
        //没有限购的特价商品
        let curGoodsLimitObj = {};
        let curPidIdx = res.data.on_sale_product_arr.indexOf(params.id);
        if (curPidIdx != -1) {
          //当前被限制的商品的限制数量
          curGoodsLimitObj = data[curPidIdx];
          params.limit = curGoodsLimitObj.day_limit_buy - curGoodsLimitObj.buyed_num;
          params.day_limit_buy = curGoodsLimitObj.day_limit_buy;
          this.limit = params.limit;
          console.log(curGoodsLimitObj);
        } else {
          curGoodsLimitObj = data[0]
          params.limit = curGoodsLimitObj.day_limit_buy - curGoodsLimitObj.buyed_num;
          params.day_limit_buy = curGoodsLimitObj.day_limit_buy;
          this.limit = params.limit;
        }
        if (curGoodsLimitObj.buyed_num != 0 && curPidIdx != -1) {
          this.$helper.toast('特价商品每天只能购买一次');
          return;
        }
        if (res.data.check_status) {
          shopingCarList.forEach(elem => {
            if (elem.id == params.id) {
              isHave = true;
              if (isNewGoods) {
                this.$helper.toast('新人商品只能添加一个!');
              } else {
                console.log(elem.num, params.limit, 999999999)
                if (elem.num < params.limit) {
                  elem.num += params.num;
                  this.$helper.toast('已添加进购物车');
                  elem.limit = params.limit;
                  elem.day_limit_buy = params.day_limit_buy;
                } else {
                  this.$helper.toast(
                    `今日商品限购${curGoodsLimitObj.day_limit_buy}件,超过购买数量`);
                }
              }
            }
          })
          if (!isHave) {
            if (params.limit > 0) {
              shopingCarList.push(params);
              this.$helper.toast('已添加进购物车');
            } else {
              // shopingCarList.push(params);
              this.$helper.toast(
                `今日商品限购${params.day_limit_buy}件,超过购买数量`);
            }

          }
          this.SET_SHOPING_CAR_LIST(shopingCarList);


          this.buyNum = 1;
          this.buyGoodsShow = false;
          this.$emit('submitGetGoods', params);
        }
        //限购的特价商品
        else {
          let orgGoods = {
            id: '',
            img: '',
            name: '',
            price: ''
          }

          //循环证明购物车里已经有了特价商品种类
          shopingCarList.forEach(item => {
            let id_index = res.data.on_sale_product_arr.indexOf(item.id);
            if (id_index != -1) {
              orgGoods = {
                id: item.id,
                img: item.images[0],
                name: item.name,
                price: item.price,
                num: item.num,
                limit: item.limit,
                day_limit_buy: item.day_limit_buy,
              }
            }
          })
          this.curGoodsBox = {
            orgGoods,
            newGoods: {
              id: params.id,
              img: params.images[0],
              name: params.name,
              price: params.price,
              day_limit_buy: params.day_limit_buy,
              limit: params.limit,
            }
          }

          if (orgGoods.id && res.data.on_sale_product_arr.indexOf(params.id) != -1 && this
            .curGoodsBox.orgGoods.id != this.curGoodsBox.newGoods.id) {
            this.limitShow = true;
            return;
          } else {
            this.$helper.toast('特价商品超过购买限制')
          }
        }
        return;
      })

    },
    openCar (curCarItem) {
      this.curCarItem = curCarItem;
      this.$refs.buyGoodsPopup.buyGoodsShow = true;
    },
    getUserLocation () {
      let that = this;
      uni.getFuzzyLocation({
        type: 'gcj02', //返回可以用于uni.openLocation的经纬度
        geocode: true, //是否解析地址
        success: function (res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          console.log(res, '当前定位');
          that.getLocal(latitude, longitude);
        },
        fail: function (err) {
          console.log(err, '获取定位失败');
          // that.$helper.toast('请打开定位服务功能！');
          uni.showModal({
            title: '定位权限',
            content: '店铺列表需要根据您的当前位置定位推送，请开启定位权限',
            success (res) {
              console.log('showModal确定');
            }
          });
        }
      });
    },

    // 获取当前地理位置
    getLocal (latitude, longitude) {
      let that = this;
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: res => {
          that.addressObj.address = res.result.address;
          that.addressObj.latitude = latitude;
          that.addressObj.longitude = longitude;
          uni.setStorageSync('address', that.addressObj);
          //获取到地址信息后请求自提点列表
          that.getTeamList();
        },
        fail: res => {
          console.log(res);
        },
        complete: res => { }
      });
    },
    getTeamList () {
      const {
        latitude,
        longitude
      } = this.addressObj;
      let params = {
        ...this.page,
        latitude,
        longitude
      };
      this.tempPage = {
        page: 1,
        page_size: 6
      };
      this.getList('teamListObj', 'getTeamList', 'tempPage', params).then(res => {
        this.curAddressGetPoint = res.lists[0];
        uni.setStorageSync('cur_address_point', res.lists[0]);
        this.getClassify();
        this.getRecommend();
        this.getProductList({
          team_id: this.curAddressGetPoint.id
        }, 'init');
        this.getNewcomerList();
        this.getCouponsList();
      });
    },
    //获取优惠券列表
    getCouponsList () {
      let token = uni.getStorageSync('token');
      let couponsShow = uni.getStorageSync('couponsShow');
      if (token && couponsShow) {
        this.$api.getTeamTicket().then(res => {
          if (res.data.length) {
            this.couponsShow = true;
            uni.setStorageSync('couponsShow', false);
            this.ticket = res.data.map(item => {
              return {
                ...item,
                price: parseInt(item.price),
                full_use: parseInt(item.full_use),
                start_date: this.$helper.formatDate(item.start_date, 'yyyy.MM.dd'),
                end_date: this.$helper.formatDate(item.end_date, 'yyyy.MM.dd')
              };
            });
          }
        });
      }
    },
    //关闭优惠券模态框
    couponsClose () {
      this.couponsShow = false;
    },
    //领取优惠券
    getTicket (id) {
      this.$api.getTicket({
        ids: id
      }).then(res => {
        console.log(res, '获取优惠券');
        if (res.code == 1) {
          this.ticket = this.ticket.filter(item => item.id != id);
          this.$helper.toast(res.msg);
          if (!this.ticket.length) {
            this.couponsShow = false;
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
.shop {
  background-color: #f9f9f9;
  padding: 0rpx 24rpx 100rpx;

  .fix_top_box {
    position: sticky;
    top: 0;
    left: 0;
    background-color: #f9f9f9;
    padding-bottom: 10rpx;
    z-index: 99;
  }

  .address_box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 35rpx;
  }

  .search_box {
    height: 68rpx;
    background: #ffffff;
    border-radius: 34rpx;
    border: 2rpx solid #fed100;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;

    .left_search_box {
      padding-left: 18rpx;
      display: flex;
      align-items: center;

      .search_icon {
        margin-right: 4rpx;
      }

      .search_input {
        color: #a7a7a7;
        font-size: 26rpx;
      }
    }

    .search_btn {
      button {
        width: 120rpx;
        height: 68rpx;
        background: #fed100;
        font-size: 26rpx;
        border-radius: 34rpx;
      }
    }
  }

  .carousel_box {
    margin-bottom: 30rpx;
  }

  .classify_list_box {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx 34rpx;
    margin-bottom: 20rpx;

    .classify_item {
      text-align: center;
      margin-bottom: 27rpx;
    }
  }

  .newcomer_box {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .newcomer_top_box {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .more_btn {
        display: flex;
        align-items: center;
      }
    }

    .newcomer_list_box {
      .newcomer_scroll_box {
        position: relative;
        width: 100%;
        height: 340rpx;
        overflow: hidden;
        box-sizing: border-box;

        .innerList {
          display: flex;
        }

        .newcomer_shop_item {
          margin-right: 20rpx;
          width: 180rpx;

          .newcomer_shop_item_img {
            margin-bottom: 10rpx;

            image {
              width: 180rpx;
              height: 180rpx;
              border-radius: 10rpx;
            }
          }

          .newcomer_shop_item_name {
            margin-bottom: 10rpx;
            height: 80rpx;
            font-size: 28rpx;
            overflow: hidden;
            -webkit-line-clamp: 2;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
          }

          .newcomer_shop_item_price_box {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .price_num {
            }

            .add_shoping_car {
            }
          }
        }
      }
    }
  }

  .recommend_box {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .big_recommend_list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10rpx;

      .big_recommend_item {
        image {
          width: 322rpx;
          height: 187rpx;
          border-radius: 10rpx;
        }
      }
    }

    .small_recommend_list {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .small_recommend_item {
        image {
          width: 156rpx;
          height: 156rpx;
          border-radius: 10rpx;
        }
      }
    }
  }

  .goods_list {
  }

  .fix_shoping_car {
    position: fixed;
    bottom: 0;
    width: 100vw;
    left: 0;

    .shoping_car_bottom_op_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      padding: 24rpx;

      .shoping_car_bottom_left_box {
        padding-left: 120rpx;
        position: relative;

        .shoping_car_image {
          position: absolute;
          left: 0;
          top: -54rpx;

          .shoping_car_num {
            position: absolute;
            right: -8rpx;
            top: -6rpx;
            background-color: #f34035;
            border-radius: 50%;
            color: #fff;
            font-size: 26rpx;
            width: 40rpx;
            text-align: center;
            line-height: 40rpx;
            height: 40rpx;
          }
        }

        .shoping_car_total_pirce_box {
        }
      }

      .go_settle {
        color: #333;
        font-weight: bold;
        font-size: 30rpx;
        padding: 15rpx 30rpx;
        background-color: #fed100;
        border-radius: 40rpx;
      }
    }
  }

  .couponsModel {
    background: #ffffff;
    border-radius: 20rpx 20rpx 0px 0px;
    padding: 30rpx 20rpx;

    .coupons_model_top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 25rpx;
    }

    .coupons_scroll_box {
      height: 50vh;
    }

    .coupons_list {
      .coupons_item {
        display: flex;
        width: 100%;
        height: 184rpx;
        align-items: center;
        background: url("../../static/images/icon/bg_coupons.png") no-repeat;
        background-size: 100% 184rpx;
        box-sizing: border-box;
        padding: 33rpx 39rpx;
        margin-bottom: 17rpx;

        .coupons_left_price_box {
          margin-right: 67rpx;
        }

        .coupons_right_date_box {
        }
      }
    }
  }
}
</style>